package handler

import (
	pb "captcha/proto/captcha"
	"context"
	"github.com/mojocn/base64Captcha"
	"image/color"
)

type Captcha struct{}

var store = base64Captcha.DefaultMemStore

// 获取验证码的方法
func (e *Captcha) MakeCaptcha(ctx context.Context, req *pb.MakeCaptchaRequest, res *pb.MakeCaptchaResponse) error {
	var driver base64Captcha.Driver             //驱动程序变量 driver
	driverString := base64Captcha.DriverString{ // 用来生成字符串的字符串驱动
		Height:          int(req.Height),
		Width:           int(req.Width),
		NoiseCount:      0,
		ShowLineOptions: 2 | 4,
		Length:          int(req.Length),
		Source:          "1234567890qwertyuiopasdfghjklzxcvbnm",
		BgColor: &color.RGBA{
			R: 102,
			G: 102,
			B: 214,
			A: 125,
		},
		Fonts: []string{"wqy-microhei.ttc"},
	}
	driver = driverString.ConvertFonts()         // 将字体转换为驱动程序变量
	c := base64Captcha.NewCaptcha(driver, store) //创建了一个验证码实例
	id, b64s, _, err := c.Generate()             // 生成验证码
	res.Id = id
	res.B64S = b64s
	return err
}

// 检验验证码
func (e *Captcha) VerifyCaptcha(ctx context.Context, req *pb.VerifyCaptchaRequest, res *pb.VerifyCaptchaResponse) error {
	if store.Verify(req.Id, req.VerifyValue, true) { // true表示在验证成功之后删除验证码
		res.VerifyResult = true
	} else {
		res.VerifyResult = false
	}
	return nil
}
